package blog.hibernate;

import java.util.Collection;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import blog.model.User;

@Transactional
@Repository
public class UserHibernate {

	@Autowired
	private transient SessionFactory sessionFactory;

	public void createUser(User obj) {
		sessionFactory.getCurrentSession().save(obj);
	}

	public void updateUser(User obj) {
		sessionFactory.getCurrentSession().update(obj);
	}

	@Transactional(readOnly = true)
	public User findUser(int id) {
		return (User) sessionFactory.getCurrentSession().get(User.class, id);
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public Collection<User> findUsers() {
		return sessionFactory.getCurrentSession().createCriteria(User.class)
				.list();
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public boolean checkUserLogin(String email, String password) {
		List<User> list = sessionFactory
				.getCurrentSession()
				.createQuery(
						"from User b where b.email = :email and b.password = :password")
				.setParameter("email", email)
				.setParameter("password", password).list();
		return list.size() > 0 ? true : false;
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public boolean isExistEmailUser(String email) {
		List<User> list = sessionFactory.getCurrentSession()
				.createQuery("from User b where b.email = :email")
				.setParameter("email", email).list();
		return list.size() > 0 ? true : false;
	}

}
